package com.kayang.webapi.tool;


import com.kayang.nadapt.util.StringUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 封装一个表示Sql语句的简易类型
 */
public class SqlScript {
	// SQL语句的主体
	public String SqlTxt;

	// 存储SQL语句里的所有变量
	public Map<String, SqlParaPair> SqlParas;

	public SqlScript(String _sqlTxt) throws Exception{
		this.SqlTxt = _sqlTxt;
		HandleSqlTxt();
	}

	@SuppressWarnings({ "unchecked", "rawtypes" })
	private void HandleSqlTxt() throws Exception{
		String mySqlTxt = !StringUtil.isNullOrEmpty(this.SqlTxt) ? this.SqlTxt : "";
		mySqlTxt = mySqlTxt.trim();

		String[] varibles = RegMatchParas(mySqlTxt);
		Map sqlParas = new HashMap<String, SqlParaPair>();
		for (int i = 0; i < varibles.length; i++) {
			SqlParaPair p = new SqlParaPair();
			p.ParaName = varibles[i];
			p.ParaValue = null;
			String key = StringUtil.format("@{0}", i + 1);
			sqlParas.put(key, p);
		}
		this.SqlParas = sqlParas;
		this.SqlTxt = MarkSqlParas();

	}

	private String MarkSqlParas() {
		String mySqlTxt = !StringUtil.isNullOrEmpty(this.SqlTxt) ? this.SqlTxt : "";
		mySqlTxt = mySqlTxt.trim();
		for (String key : this.SqlParas.keySet()) {
			int pos = mySqlTxt.toLowerCase().indexOf("{" + this.SqlParas.get(key).getParaName().toLowerCase() + "}"); // 忽略大小写
			if (pos > 0) {
				mySqlTxt = StringUtil.format("{0}{1}{2}", mySqlTxt.substring(0, pos), key,
						mySqlTxt.substring(pos + 2 + this.SqlParas.get(key).getParaName().length()));
			}
		}
		return mySqlTxt;
	}

	private String[] RegMatchParas(String mySqlTxt) {
		// 根据正则表达式分隔字符串，并将其放进字符串数组
		Pattern r = Pattern.compile("\\{([^\\}]*)\\}");
		Matcher matcher = r.matcher(mySqlTxt);
		ArrayList<String> values = new ArrayList<>();
		while (matcher.find()) {
			values.add(matcher.group(0));
		}
		String[] strs = values.toArray(new String[0]);
		int i = 0;
		for (String str : strs) {
			strs[i]=str.replace("{", "").replace("}", "");
			i++;
		}
		return strs;
	}

	// 代表着参数的value的对象
	public static class SqlParaPair {
		public String ParaName;

		public Object ParaValue;

		public String getParaName() {
			return ParaName;
		}

		public void setParaName(String paraName) {
			ParaName = paraName;
		}

		public Object getParaValue() {
			return ParaValue;
		}

		public void setParaValue(Object paraValue) {
			ParaValue = paraValue;
		}

	}

	public String getSqlTxt() {
		return SqlTxt;
	}

	public void setSqlTxt(String sqlTxt) {
		SqlTxt = sqlTxt;
	}

	public Map<String, SqlParaPair> getSqlParas() {
		return SqlParas;
	}

	public void setSqlParas(Map<String, SqlParaPair> sqlParas) {
		SqlParas = sqlParas;
	}

}
